from django.db import models

class ProvincePatent(models.Model):
    """省份专利数据"""
    province = models.CharField(max_length=50, verbose_name='省份')
    count = models.IntegerField(verbose_name='专利数量')
    industry = models.CharField(max_length=100, verbose_name='产业', default='新材料', db_index=True)
    
    class Meta:
        db_table = 'province_patents'
        verbose_name = '省份专利数据'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.province} ({self.industry}): {self.count}"


class Keyword(models.Model):
    """核心词表"""
    keyword = models.CharField(max_length=100, unique=True, verbose_name="核心词")
    count = models.IntegerField(verbose_name="出现次数")
    industry = models.CharField(max_length=100, verbose_name='产业', default='新材料', db_index=True)
    
    class Meta:
        db_table = 'keywords'
        verbose_name = '核心词'
        verbose_name_plural = verbose_name

    def __str__(self):
        return f"{self.keyword} ({self.industry}): {self.count}"


class WordPair(models.Model):
    """词对共现关系表"""
    kword1 = models.ForeignKey(Keyword, on_delete=models.CASCADE, related_name='pairs_as_first', verbose_name="核心词1")
    kword2 = models.ForeignKey(Keyword, on_delete=models.CASCADE, related_name='pairs_as_second', verbose_name="核心词2")
    co_count = models.IntegerField(verbose_name="共现次数")
    
    class Meta:
        db_table = 'word_pairs'
        verbose_name = '词对关系'
        verbose_name_plural = verbose_name
        unique_together = ('kword1', 'kword2')

    def __str__(self):
        return f"{self.kword1.keyword} & {self.kword2.keyword}: {self.co_count}"


class TopOrg(models.Model):
    """机构专利排名模型"""
    org = models.CharField('机构名称', max_length=200, unique=True)
    count = models.IntegerField('专利数量')
    industry = models.CharField(max_length=100, verbose_name='产业', default='新材料', db_index=True)

    class Meta:
        db_table = 'top_orgs'
        verbose_name = '机构专利排名'
        verbose_name_plural = '机构专利排名'
        ordering = ['-count']

    def __str__(self):
        return f"{self.org} ({self.industry}): {self.count}"


class WordTrend(models.Model):
    """核心词年度趋势"""
    year = models.IntegerField(verbose_name='年份')
    word = models.CharField(max_length=100, verbose_name='核心词')
    patent_count = models.IntegerField(verbose_name='专利数量')
    count = models.IntegerField(verbose_name='词出现数量')
    industry = models.CharField(max_length=100, verbose_name='产业', default='新材料', db_index=True)
    
    class Meta:
        db_table = 'word_trends'
        verbose_name = '核心词趋势'
        verbose_name_plural = verbose_name
        unique_together = [('year', 'word')]
        indexes = [
            models.Index(fields=['year', 'word'], name='word_trends_year_word_idx'),
            models.Index(fields=['word'], name='word_trends_word_idx'),
        ]
        
    def __str__(self):
        return f"{self.word} ({self.year}): {self.patent_count}"